// 测试文件上传

const path = require('path');
const fs = require('fs');

const express = require('express');
const multer = require('multer');

//const upload = multer({ dest: 'uploads/' });

/*
const storage = {
    destination: (req, file, callback) => {
        console.log(file);
        callback(null, path.join(__dirname, 'uploads'));
    },
    filename: (req, file, callback) => {
        console.log(file);
        callback(null, file.fieldname + '-' + Date.now());
    }
}*/

// 表示将上传的文件内容先存储在内存中
const storage = multer.memoryStorage();

const upload = multer({ storage: storage });

const port = 8080;
const app = express();

// 处理静态资源( HTML / CSS / JavaScript / Images )
app.use(express.static('public'));

app.get('/', (req, resp) => {
    resp.redirect('/upload.html');
});

// <input type="file" name="upfile">
app.use('/upload/single', upload.single('upfile'));

app.post('/upload/single', (req, resp, next) => {
    let file = req.file;
    let pathname = path.join(__dirname, 'uploads', file.originalname);
    console.log(pathname);

    let dirname = path.dirname(pathname);
    let basename = path.basename(pathname);
    let extname = path.extname(pathname);
    let index = basename.indexOf(extname);
    if (index != -1) {
        basename = basename.substring(0, index);
    }
    pathname = dirname + path.sep + basename + '_' + Date.now() + extname;
    console.log(pathname);

    fs.writeFile(pathname, file.buffer, (error) => {
        if (error) {
            resp.send('<h3>上传失败</h3>');
        } else {
            resp.send('<h3>上传成功</h3>');
        }
    });

});

// <input type="file" name="upfile" multiple>
app.use('/upload/multiple', upload.fields([{ name: 'upfile', maxCount: 5 }]));

// <input type="file" name="upfile" multiple>
app.post('/upload/multiple', (req, resp, next) => {
    // 需要通过 req.files[ fieldName] 来获取相应的文件数组
    let files = req.files['upfile'];
    console.log(files);
    files.forEach(file => {
        let pathname = path.join(__dirname, 'uploads', file.originalname);
        console.log(pathname);
        let dirname = path.dirname(pathname);
        let basename = path.basename(pathname);
        let extname = path.extname(pathname);
        let index = basename.indexOf(extname);
        if (index != -1) {
            basename = basename.substring(0, index);
        }
        pathname = dirname + path.sep + basename + '_' + Date.now() + extname;

        fs.writeFile(pathname, file.buffer, (error) => {
            console.log(error);
        });
    });
    resp.send('<h3>回来是回来了，上传成功没有就不知道了</h3>');
});

app.listen(port, () => {
    console.log(`启动监听(${__filename})`);
});